<template>
  <div>
    <el-dialog :title="types=='add'?'新增':'修改'" :visible="isShow" :before-close="close" width="50%">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="ruleForm.rolename"></el-input>
        </el-form-item>
        <el-form-item label="角色权限">
          <el-tree :data="treeData" show-checkbox default-expand-all node-key="id" ref="tree" highlight-current :props="defaultProps">
          </el-tree>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="ruleForm.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="2">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="close">取消</el-button>
        <el-button @click="submit" type="primary">
          确定
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { addRole, editRole } from '@/api/index'
export default {
  name: 'MyWin',
  props: ['isShow', 'winList', 'types'],
  data () {
    return {
      // 树形控件的数据
      treeData: [],
      // 树形控件的配置
      defaultProps: {
        children: 'children',
        label: 'title' // 文字
      },
      // 表单数据
      ruleForm: {
        roleName: '',
        menus: '',
        status: 1
      },
      rules: {
        name: [{ required: true, message: '请输入角色名字', trigger: 'blur' }]
      }
    }
  },
  methods: {
    close () {
      this.$emit('updates')
    },
    submit () {
      this.$refs.ruleForm.validate(async valid => {
        if (valid) {
          // 获取用户勾选的菜单对应的id
          this.ruleForm.menus = this.$refs.tree.getCheckedKeys().join()
          // 校验成功就可以提交数据了
          let res
          // eslint-disable-next-line
          if (this.types == 'add') {
            res = await addRole(this.ruleForm)
          } else {
            res = await editRole(this.ruleForm)
          }
          // eslint-disable-next-line
          if (res.code == 200) {
            this.$emit('update')
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
      // 调用关闭函数
      this.close()
    },
    setVal (data) {
      // 给表单项赋值，根据数据，在页面勾选对应的内容，实质是控制输入框（获取值，设置值）
      const arrTem = data.menus.split(',')
      // 第一次打开弹窗的时候，因为dom更新是异步的，此时tree还没加载，所有this.$refs.tree不存在
      // 避免报错需要setCheckedKeys函数延迟执行，这个时候就用到$nextTick这个钩子函数了
      this.$nextTick(() => {
        // DOM更新之后才会执行这一句
        this.$refs.tree.setCheckedKeys([...arrTem])
      })
      this.ruleForm = { ...data }
    },
    getMenulist () {
      this.$requests('/menulist?istree=1').then(res => {
        this.treeData = res.list
      })
    }
  },
  created () {
    // 发请求 获取树形控件的数据
    this.getMenulist()
  }
}
</script>

<style lang="less" scoped>
</style>
